package com.movieknight;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import com.github.savvasdalkitsis.jtmdb.Country;
import com.github.savvasdalkitsis.jtmdb.Movie;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.CheckBox;
import android.widget.Toast;

// AddMovieInfoPageActivty shows the information about a movie.
// It gives the user the ability to add the movie to their collection or watch a Trailer.

public class MovieInfoPageActivity extends Activity implements OnCheckedChangeListener {
	private static final String LOG_TAG = TMDBMovieDownloader.class.getSimpleName();
	Socket server = null;
	TextView errorCode = null;
	String imdb;
	String movieRating; 
	int rating;
	
	private int movieID;
	@SuppressWarnings("unused")
	private static final SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
	@SuppressWarnings("unused")
	private static final DateFormat dfLocal = DateFormat.getDateInstance();

	int getMovieID() {
		return movieID;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		// Set up view and start progress bar
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.moviealt);
		setProgressBarIndeterminateVisibility(true);
		
		// get the movie id and then the movie
		Bundle extras = getIntent().getExtras();
		movieID = extras.getInt("movieID");
		setFields(movieID);
		
		// stop the progress bar
		setProgressBarIndeterminateVisibility(false);

		try {
			Movie temp = Movie.getInfo(getMovieID());
			imdb = temp.getImdbID();
			
			if(server == null) {
				server = new Socket("nss324-39.cse.tamu.edu",50001);
			}
			
			if(server!=null) {
	    		((MovieKnightApp) this.getApplication()).setServer(server);
			}
			
			((MovieKnightApp) this.getApplication()).getServer();
			
            try {
            	PrintWriter out = null;
				out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
				out.println("{\"module\": \"movies\", \"method\": \"get_rating\", \"session_id\": \"" + ((MovieKnightApp) this.getApplication()).getSessionID() + "\", \"params\": {\"movie_id\": \"" + imdb + "\"}}");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
            
    		//read line(s)
	        BufferedReader input;
	        input = new BufferedReader(new InputStreamReader(server.getInputStream()));
	        
	        String st = input.readLine();
			Log.v(LOG_TAG, "st: " + st);

			JSONObject jsonObject = new JSONObject(st);
			if(jsonObject.has("rating") && jsonObject.getInt("error_code") == 0) {
				movieRating = jsonObject.getString("rating");
				Log.v(LOG_TAG, "movieRating: " + movieRating);
				try {
				    rating = Integer.parseInt(movieRating);
				}
				catch(NumberFormatException nfe) {
					Log.w(LOG_TAG, "Conversion Error");
				}
			}
			else {
				rating = 0;
			}
			Log.v(LOG_TAG, "rating: " + rating);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
		
		CheckBox star1 = ( CheckBox ) findViewById(R.id.star1);
		CheckBox star2 = ( CheckBox ) findViewById(R.id.star2);
		CheckBox star3 = ( CheckBox ) findViewById(R.id.star3);
		CheckBox star4 = ( CheckBox ) findViewById(R.id.star4);
		CheckBox star5 = ( CheckBox ) findViewById(R.id.star5);

		switch(rating) {
			case 0:
				star1.setChecked(false);
				star2.setChecked(false);
				star3.setChecked(false);
				star4.setChecked(false);
				star5.setChecked(false);
			break;
			
			case 1:
				star1.setChecked(true);
				star2.setChecked(false);
				star3.setChecked(false);
				star4.setChecked(false);
				star5.setChecked(false);
			break;
			
			case 2:
				star1.setChecked(true);
				star2.setChecked(true);
				star3.setChecked(false);
				star4.setChecked(false);
				star5.setChecked(false);
			break;
			
			case 3:
				star1.setChecked(true);
				star2.setChecked(true);
				star3.setChecked(true);
				star4.setChecked(false);
				star5.setChecked(false);
			break;
			
			case 4:
				star1.setChecked(true);
				star2.setChecked(true);
				star3.setChecked(true);
				star4.setChecked(true);
				star5.setChecked(false);
			break;
			
			case 5:
				star1.setChecked(true);
				star2.setChecked(true);
				star3.setChecked(true);
				star4.setChecked(true);
				star5.setChecked(true);
			break;
		}

		star1.setOnCheckedChangeListener(this);
		star2.setOnCheckedChangeListener(this);
		star3.setOnCheckedChangeListener(this);
		star4.setOnCheckedChangeListener(this);
		star5.setOnCheckedChangeListener(this);
		
	}
	
	private void setFields(int movieID) {
		// replace by get movie by id... at the moment, we get it by list
		// position from most popular
		final Movie movie = TMDBMovieDownloader.get(movieID);

		// collect fields for primary information
		TextView movieName = (TextView) findViewById(R.id.movieName);
		ImageView moviePoster = (ImageView) findViewById(R.id.moviePoster);
		TextView movieAlternativeName = (TextView) findViewById(R.id.movieAlternativeName);
		TextView movieRelease = (TextView) findViewById(R.id.movieRelease);
		TextView movieOverview = (TextView) findViewById(R.id.movieOverview);
		TextView movieCountry = (TextView) findViewById(R.id.movieCountry);
		TextView movieLanguage = (TextView) findViewById(R.id.movieLanguage);
		Button movieTrailer = (Button) findViewById(R.id.movieTrailer);

		movieName.setText(movie.getName());

		if (movie.getImages().posters != null
				&& movie.getImages().posters.iterator().hasNext()) {
			String url = movie.getImages().posters.iterator().next()
					.getSmallestImage().toString();
			Log.d("ShowMovieActivity", url);
			MovieKnightApp.imageDownloader.download(url, moviePoster);
		} else {
			moviePoster.setVisibility(View.GONE);
		}
		
		MovieKnightApp app = (MovieKnightApp) getApplication();
		String secondary = app.chooseSecondaryName(movie, true);
		
		if (secondary.equals("null")) {
			movieAlternativeName.setVisibility(View.GONE);
		} else {
			movieAlternativeName.setText(secondary);
		}

		if (movie.getReleasedDate() != null) {
			movieRelease.setText(getString(R.string.movieRelease) + " " + android.text.format.DateFormat.getDateFormat(getApplicationContext()).format(movie.getReleasedDate()));
			this.setTitle(movie.getName() + " (" + MovieKnightApp.sdfYear.format(movie.getReleasedDate()) + ")");
		} else {
			movieRelease.setVisibility(View.GONE);
			this.setTitle(movie.getName());
		}

		if (movie.getLanguage() != null && movie.getLanguage().length() > 0) {
			Locale locale = new Locale(movie.getLanguage());
			movieLanguage.setText(locale.getDisplayLanguage());
		} else {
			movieLanguage.setVisibility(View.GONE);
			findViewById(R.id.movieLanguageTitle).setVisibility(View.GONE);
		}

		if (movie.getCountries() != null
				&& movie.getCountries().iterator().hasNext()) {
			String countries = new String();
			Locale locale;

			for (Country country : movie.getCountries()) {
				locale = new Locale(Locale.getDefault().getLanguage(), country
						.getCode());
				countries += locale.getDisplayCountry() + ", ";
				Log.d("ShowMovieActivity", country.getCode() + "->"
						+ locale.getDisplayCountry());

			}
			// cut off the last coma and space when setting the countries
			movieCountry.setText(countries.subSequence(0,
					countries.length() - 2));
		} else {
			movieCountry.setVisibility(View.GONE);
			findViewById(R.id.movieCountryTitle).setVisibility(View.GONE);
		}

		if (movie.getOverview() != null && !movie.getOverview().equals("null")) {
			movieOverview.setText(movie.getOverview());
		} else {
			movieOverview.setVisibility(View.GONE);
			findViewById(R.id.movieOverviewTitle).setVisibility(View.GONE);
		}

		if (movie.getTrailer() != null) {
			movieTrailer.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					final String url = movie.getTrailer().toString();
					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
					}
			});
		}
		else {
			movieTrailer.setVisibility(View.GONE);
			findViewById(R.id.movieTrailerTitle).setVisibility(View.GONE);
		}	
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

		CheckBox star1 = ( CheckBox ) findViewById(R.id.star1);
		CheckBox star2 = ( CheckBox ) findViewById(R.id.star2);
		CheckBox star3 = ( CheckBox ) findViewById(R.id.star3);
		CheckBox star4 = ( CheckBox ) findViewById(R.id.star4);
		CheckBox star5 = ( CheckBox ) findViewById(R.id.star5);
		
		star1.setOnCheckedChangeListener(null);
		star2.setOnCheckedChangeListener(null);
		star3.setOnCheckedChangeListener(null);
		star4.setOnCheckedChangeListener(null);
		star5.setOnCheckedChangeListener(null);
		
        switch(buttonView.getId()){
        case R.id.star1:
    		star1.setChecked(true);
        	star2.setChecked(false);
        	star3.setChecked(false);
        	star4.setChecked(false);
        	star5.setChecked(false);
        	rating = 1;
        break;
        
        case R.id.star2:
    		star1.setChecked(true);
        	star2.setChecked(true);
        	star3.setChecked(false);
        	star4.setChecked(false);
        	star5.setChecked(false);
        	rating = 2;
        break;

        case R.id.star3:
    		star1.setChecked(true);
        	star2.setChecked(true);
        	star3.setChecked(true);
        	star4.setChecked(false);
        	star5.setChecked(false);
        	rating = 3;
        break;

        case R.id.star4:
    		star1.setChecked(true);
        	star2.setChecked(true);
        	star3.setChecked(true);
        	star4.setChecked(true);
        	star5.setChecked(false);
        	rating = 4;
        break;

        case R.id.star5:
    		star1.setChecked(true);
        	star2.setChecked(true);
        	star3.setChecked(true);
        	star4.setChecked(true);
        	star5.setChecked(true);
        	rating = 5;
        break;
        }
        
        try {
        	PrintWriter out = null;
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
			out.println("{\"module\": \"movies\", \"method\": \"rate_movie\", \"session_id\": \"" + ((MovieKnightApp) this.getApplication()).getSessionID() + "\", \"params\": {\"movie_id\": \"" + imdb + "\", \"rating\": " + rating + "}}");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        JSONObject jobj = new JSONObject();
        try {
			jobj.put(String.valueOf(getMovieID()), rating);
		} catch (JSONException e) {
			e.printStackTrace();
		}
        
		star1.setOnCheckedChangeListener(this);
		star2.setOnCheckedChangeListener(this);
		star3.setOnCheckedChangeListener(this);
		star4.setOnCheckedChangeListener(this);
		star5.setOnCheckedChangeListener(this);
	}
}
